<?php
namespace app\open\model;
use app\common\model\OpenBase;

class UserData extends OpenBase {
	protected $tableName = 'user_data'; //user信息表
	//定义字段信息
	protected $fields = [
		0 => 'id',
		1 => 'uid',
		2 => 'gold',
		3 => 'zan_count',
		4 => 'zan_remain',
        5 => 'live_time',
        6 => 'view_count',
        7 => 'is_sync',
		'_pk' => 'id',
	];
	//设置自动填充的数据
	protected $auto = [];
	//初始化方法
	protected function _initialize() {
       \think\Config::load(join(DIRECTORY_SEPARATOR, array(APP_PATH, 'api', 'config.php')));
	}
    /**
	 * @name 添加用户的数据记录
	 * @access public
	 * @param int $uid 用户UID
	 * @param string $field 数据字段
	 * @param int $value 需要添加的值
	 * @return string 添加的结果
	 */
	public function dataInco($uid = 0, $field = '', $value = 0) {
		if (!$uid || !$field) {
			return false;
		}
		//初始化data统计数据
		if (!$this->where('uid=' . $uid)->find()) {
			$this->add(['uid' => $uid]);
		}
		if ($field == 'view_count') {
			if ($this->getFieldByUid($uid, 'view_count') != $value) {
				$value > 0 && $this->where('uid=' . $uid)->setField($field, $value);
			}
			return 1;
		} elseif ($value <= 0) {
			return 1;
		}
        
		if($this->where('uid=' . $uid)->setInc($field, $value)){
		   return $this->syncData($uid);
		}
        return false;
	}
	/**
	 * @name 减少用户的数据记录
	 * @access public
	 * @param int $uid 用户UID
	 * @param string $field 数据字段
	 * @param int $value 需要添加的值
	 * @return string 添加的结果
	 */
	public function dataDeco($uid = 0, $field = '', $value = 0) {
		if (!$uid || !$field || !$value) {
			return false;
		}
		if (!$this->where('uid=' . $uid)->find()) {
			$this->add(['uid' => $uid]);
			return 1;
		}
		return $this->where('uid=' . $uid)->setDec($field, $value);
	}
    /**
     * @name 请求在客户服务器上进行消费
     */
    public function checkUserPay($data = []){
        //$conf = C('conf_service_api.user_give_gift_conf')?:'';
        $conf = model('admin/Config')->getConfigValue(['type'=>'sync','key'=>'user_give_gift_conf']);
        if($conf){
            $conf['method'] = in_array($conf['method'],['get','post']) ? $conf['method'] : 'post';
            if($conf['method'] == 'post'){
                $data = array_merge($conf['data'],$data);
            }
            if(is_array($conf['header'])){
                $this->header = $conf['header'];
            }
            $res = self::request($conf['method'],$data,$conf['url']);
            if(is_json($res)){
                $res = json_decode($res,true);
            }
            if($res['status'] == 1){
                M('gift_give_log')->where(['order'=>$data['order']])->delete();
                return true;
            }
            $this->error = $res['message'];
            return false;
        }
        $this->error = '赠送礼物失败';
        return false;
    }
    /**
     * @name 同步直播服务器所需要的统计数据
     */
    public function syncData($uid = 0){
        if(!$uid) return false;
        //$conf = C('conf_service_api.user_data_sync_conf')?:'';
        $conf = model('admin/Config')->getConfigValue(['type'=>'sync','key'=>'user_data_sync_conf']);
        if($conf){
            $data['usid'] = model('open/User')->getUsidByUid($uid);
            $local_data = $this->getUserAccount($uid);
            $data['data'] = [
                'gold' => $local_data['gold'],
                'zan_count' => $local_data['zan_count'],
                'zan_remain' => $local_data['zan_remain'],
                'live_time' => $local_data['live_time']
            ];
            $conf['method'] = in_array($conf['method'],['get','post']) ? $conf['method'] : 'post';
            if($conf['method'] == 'post'){
                $data = array_merge($conf['data'],$data);
            }
            if(is_array($conf['header'])){
                $this->header = $conf['header'];
            }
            
            $res = [];
            $data = self::request($conf['method'],$data,$conf['url']);
            if(is_json($data)){
                $res = json_decode($data,true);
            }
            
            if($res['status'] == 1 && $res['data']['is_sync'] == 1){
                //设置为需要同步
                //将已同步的赞数设置为0
                $local_data['zan_remain'] && $this->where(['uid'=>$uid])->setField('zan_remain',0);
                $this->setSync($uid,1);
            }elseif($res['status'] == 1 && $res['data']['is_sync'] == 0){
                $this->setSync($uid,0);
            }
        }
        return true;
    }
    /**
     * @name 获取客户服务器的用户数据
     */
    public function checkUserData($uid = 0,$request = false){
        if(!$uid) return false;
        if($this->is_sync($uid) === 1 || $request === true){
            //$conf = C('conf_service_api.user_data_get_conf')?:'';
            //获取配置
            $conf = model('admin/Config')->getConfigValue(['type'=>'sync','key'=>'user_data_get_conf']);
            if($conf){
                $data['usid'] = model('open/User')->getUsidByUid($uid);
                $conf['method'] = in_array($conf['method'],['get','post']) ? $conf['method'] : 'post';
                if($conf['method'] == 'post'){
                    $data = array_merge($conf['data'],$data);
                }
                if(is_array($conf['header'])){
                    $this->header = $conf['header'];
                }
                $data = self::request($conf['method'],$data,$conf['url']);
                $account = json_decode($data,true);
                if($account['status'] == 1){
                    $this->checkData($uid,$account['data']);
                    //设置为不需要同步
                    $this->setSync($uid,0);
                }
            }
        }
    }

    /**
     * @name 获取客户服务器的用户数据
     */
    public function checkShopOuterChain($uid = 0){
        if(!$uid) return false;
        //获取配置
        $conf = model('admin/Config')->getConfigValue(['type'=>'sync','key'=>'user_shop_outer_chain']);
        if($conf){
            $data['usid'] = model('open/User')->getUsidByUid($uid);
            $conf['method'] = in_array($conf['method'],['get','post']) ? $conf['method'] : 'post';
            if($conf['method'] == 'post'){
                $data = array_merge($conf['data'],$data);
            }
            if(is_array($conf['header'])){
                $this->header = $conf['header'];
            }
            $data = self::request($conf['method'],$data,$conf['url']);
            $account = json_decode($data,true);
            if($account['status'] == 1){
                return true;
            }

            return false;
        }
    }
    /**
     * @name 检测本地是否有数据
     */
    public function is_local($uid = 0){
        if($uid){
            return $this->where('uid='.$uid)->count() > 0 ? true : false;
        }
        return false;
    }
    /**
     * @name 检测是否需要同步
     */
    public function is_sync($uid = 0){
        if($uid){
            return (int)$this->getFieldByUid($uid,'is_sync');
        }
        return 1;
    }
    /**
     * @name 自动检测并修复统计数据
     */
    public function checkData($uid = 0,$data = []){
        if($uid && !empty($data)){
            foreach($data as $k=>$v){
                //,'zan_count','zan_remain'
                if(in_array($k,['gold']) && $this->getUserAccount($uid,$k) != $v){
                    $this->where('uid='.$uid)->setField($k,$v);
                }elseif($k == 'uname'){
                    $userModel = model('open/User');
                    if($v != $userModel->getUsername($uid)){
                        $userModel->updateField('uname',$v,'uid='.$uid);
                    }
                }elseif($k == 'sex'){
                    $userModel = model('open/User');
                    if($v != $userModel->getUserSex($uid)){
                        $userModel->updateField('sex',$v,'uid='.$uid);
                    }
                }
            }
        }
        return true;
    }
    /**
     * @name 获取指定用户账号统计信息
     */
    public function getUserAccount($uid = 0 ,$filed = ''){
        if($uid){
            if(false === $this->is_local($uid)){
                $this->add(['uid'=>$uid]);
            }
        }
        if($filed && in_array($filed,$this->fields)){
            return (int)$this->getFieldByUid($uid,$filed);
        }
        return $this->where('uid='.$uid)->find();
    }
    /**
     * @name 设置同步状态
     */
    public function setSync($uid = 0,$status = 1){
        if($this->getUserAccount($uid,'is_sync') !== $status){
            return $this->where('uid='.$uid)->setField('is_sync',$status) ? true : false;
        }
        return true;
    }
}
